#include "Game_page.h"
#include "IniProgram.h"

const int DEAD_ZONE_RADIUS = 15;

Direction calculateDirection(int deltaX, int deltaY)
{
    double distance = sqrt(deltaX * deltaX + deltaY * deltaY);
    if (distance < DEAD_ZONE_RADIUS)
        return DIRECTION_NONE;

    double angle = atan2(-deltaY, deltaX) * 180.0 / M_PI;
    if (angle < 0)
        angle += 360.0;

    if (angle >= 337.5 || angle < 22.5)
        return DIRECTION_RIGHT;
    else if (angle >= 22.5 && angle < 67.5)
        return DIRECTION_UP_RIGHT;
    else if (angle >= 67.5 && angle < 112.5)
        return DIRECTION_UP;
    else if (angle >= 112.5 && angle < 157.5)
        return DIRECTION_UP_LEFT;
    else if (angle >= 157.5 && angle < 202.5)
        return DIRECTION_LEFT;
    else if (angle >= 202.5 && angle < 247.5)
        return DIRECTION_DOWN_LEFT;
    else if (angle >= 247.5 && angle < 292.5)
        return DIRECTION_DOWN;
    else if (angle >= 292.5 && angle < 337.5)
        return DIRECTION_DOWN_RIGHT;

    return DIRECTION_NONE;
}

void Joystick_touch()
{
    gameStart();
    int touchX, touchY;
    if (Touch::getCurrentTouchPosition(touchX, touchY))
    {
        int relativeX = touchX - Joystick->get_pos_x();
        int relativeY = touchY - Joystick->get_pos_y();

        int centerX = Joystick->get_width() / 2;
        int centerY = Joystick->get_height() / 2;
        int deltaX = relativeX - centerX;
        int deltaY = relativeY - centerY;

        double distance = sqrt(deltaX * deltaX + deltaY * deltaY);
        int maxRadius = 60;

        if (distance > maxRadius)
        {
            deltaX = (deltaX / distance) * maxRadius;
            deltaY = (deltaY / distance) * maxRadius;
        }

        int new_x = centerX + deltaX - Joystick_center->get_width() / 2;
        int new_y = centerY + deltaY - Joystick_center->get_height() / 2;

        new_x = max(0, min(new_x, Joystick->get_width() - Joystick_center->get_width()));
        new_y = max(0, min(new_y, Joystick->get_height() - Joystick_center->get_height()));

        Joystick_center->set_pos(new_x, new_y);

        Direction dir = calculateDirection(deltaX, deltaY);
        if (gameSnake != nullptr && dir != DIRECTION_NONE)
        {
            gameSnake->setDirection(dir);
        }
    }
}